package com.xyxy.platform.modules.core.web.Interceptor;

import com.xyxy.platform.modules.core.spring.ResourceUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 国际化语言拦截器
 * spring mvc 配置 如下:
 * <mvc:interceptors>
 * <mvc:interceptor>
 * <mvc:mapping path="/**" />
 * <mvc:exclude-mapping path="/static/**" />
 * <bean class="com.xyxy.platform.modules.core.web.Interceptor.I18nInterceptor" />
 * </mvc:interceptor>
 * </mvc:interceptors>
 *
 * @author caizhengda
 * @version [版本号, 2016-04-20]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class I18nInterceptor extends HandlerInterceptorAdapter {

    protected static final Logger logger = LoggerFactory.getLogger(I18nInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        logger.debug("I18nInterceptor into..");

        request.setAttribute("RequestStartTime", System.currentTimeMillis());

        // 这个存在取不到的情况
        Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);

        // 默认语言,从http请求头中获取
        // Locale locale = (Locale)request.getLocales().nextElement();
        if (locale == null || StringUtils.isEmpty(locale.toString())) {
            locale = Locale.CHINA;
        }
        request.setAttribute("currentLocale", locale.toString());

        // 这里有bug，如果locale是zh-Hans-CN取不到资源文件
        if (locale.toString().toLowerCase().startsWith("zh")) {
            request.setAttribute("locale", "zh_cn");
        } else if (locale.toString().toLowerCase().startsWith("en")) {
            request.setAttribute("locale", "en_us");
        } else {
            request.setAttribute("locale", locale.toString().toLowerCase());
        }

        // 存储本地语言
        ResourceUtil.setLocale(locale);

        return super.preHandle(request, response, handler);
    }

}
